package redisclient

import (
	//	"flag"
	"fmt"
	"log"
	"swim/etc"
	"swim/util/cache"
	_ "swim/util/cache/redis"

	"time"

	"github.com/garyburd/redigo/redis"
)

var (
	G_cache     cache.Cache
	G_redisPool *redis.Pool
)

type RedisClient struct {
	pool *redis.Pool
}

//关闭redis连接池
func (c *RedisClient) Close() {
	if c.pool != nil {
		c.pool.Close()
	}
}

func NewClient(server, password string) *RedisClient {
	return &RedisClient{
		pool: newPool(server, password),
	}
}

//创建redis connection pool
func newPool(server, password string) *redis.Pool {
	return &redis.Pool{
		MaxIdle:     10,
		IdleTimeout: 300 * time.Second,
		Dial: func() (redis.Conn, error) {
			c, err := redis.Dial("tcp", server)
			if err != nil {
				return nil, err
			}

			if password != "" {
				if _, err := c.Do("AUTH", password); err != nil {
					c.Close()
					return nil, err
				}
			}
			return c, nil
		},
		TestOnBorrow: func(c redis.Conn, t time.Time) error {
			_, err := c.Do("PING")
			return err
		},
	}
}

func LoadCache() {
	redisCon := fmt.Sprintf(`{"conn":"%s:%d","password":"%s"}`,
		etc.RedisConfiger.Host, etc.RedisConfiger.Port, etc.RedisConfiger.Pwd)
	redis, err := cache.NewCache("redis", redisCon)
	if err == nil {
		G_cache = redis
	} else {
		log.Println(err.Error())
		return
	}
	redisServer := fmt.Sprintf("%s:%d", etc.RedisConfiger.Host, etc.RedisConfiger.Port)
	redisC := NewClient(redisServer, etc.RedisConfiger.Pwd)
	G_redisPool = redisC.pool
}

/*
//获取所有在线用户
func (c *redisClient) GetAll() {
	conn := c.pool.Get()
	clients, err := redis.StringMap(conn.Do("HGETALL", cacheKey))
	if err != nil {
		panic(err)
	}
	fmt.Printf("online client: %d \n", len(clients))
	for uId, client := range clients {
		fmt.Printf("%s -- %s\n", uId, client)
	}
}

//根据用户ID获取单个用户
func (c *redisClient) GetOne(id string) {
	client, err := redis.String(c.pool.Get().Do("HGET", cacheKey, id))

	if err != nil {
		panic(err)
	}
	fmt.Println(client)
}

//踢出某个用户
func (c *redisClient) Kick(id string) {
	result, err := c.pool.Get().Do("HDEL", cacheKey, id)
	if err != nil {
		panic(err)
	}
	fmt.Println(result)
}

//清除所有在线用户信息
func (c *redisClient) ClearAll() {
	result, err := c.pool.Get().Do("DEL", cacheKey)
	if err != nil {
		panic(err)
	}
	fmt.Println(result)
}*/
